<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('risk.windControl_type')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.windControlType"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
						style="width: 200px"
						@change="getMerchantDict($event)"
						@clear="clearWindControlType()"
					>
						<el-option
							v-for="item in windLevelTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.risk_control_level')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.windControlLevelName"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
						multiple
						collapse-tags
						:maxlength="10"
						:disabled="selectWindContolType"
						style="width: 260px"
					>
						<el-option
							v-for="item in windControlLevelNameArr"
							:key="item.id"
							:label="item.windControlLevelName"
							:value="item.windControlLevelName"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createBy')}:`"
					class="flex-row-container"
					label-width="61px"
				>
					<el-input
						v-model="queryData.createdBy"
						:maxlength="12"
						:placeholder="$t('risk.please_enter_createdBy')"
						v-input="{ name: 'symbols' }"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('601011')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="addLabel($t('common.add'))"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
				highlight-current-row
				@sort-change="_changeTableSort"
			>
				<el-table-column
					align="center"
					type="index"
					:label="`${$t('common.serial_number')}`"
					width="85"
				></el-table-column>
				<el-table-column
					prop="merchantId"
					align="center"
					:label="`${$t('common.belong_merchant')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ merchantFilter(scope.row.merchantId) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="windControlType"
					align="center"
					:label="`${$t('risk.windControl_type')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span v-if="!!scope.row.windControlType">
							{{
								typeFilter(
									scope.row.windControlType,
									'windLevelType'
								)
							}}
						</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="windControlLevelName"
					align="center"
					:label="`${$t('common.risk_control_level')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.windControlLevelName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="description"
					align="center"
					:label="`${$t('risk.description')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.description || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdBy"
					align="center"
					:label="`${$t('common.createBy')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="`${$t('common.createAt')}`"
					width="160"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					prop="updatedBy"
					align="center"
					:label="`${$t('common.last_updateBy')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedAt"
					align="center"
					:label="`${$t('common.last_updateAt')}`"
					width="160"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="operating"
					align="center"
					:label="`${$t('common.actions')}`"
					width="240"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('601013')"
							type="primary"
							icon="el-icon-edit"
							:disabled="loading"
							size="medium"
							@click="edit(scope.row, $t('common.edit'))"
						>
							{{ $t('common.edit') }}
						</el-button>

						<el-button
							v-if="hasPermission('601012')"
							type="danger"
							icon="el-icon-delete"
							:disabled="loading"
							size="medium"
							@click="deleteLabel(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:total="total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="
				title === $t('common.edit')
					? `${$t('risk.edit_risk_level')}`
					: `${$t('risk.add_risk_level')}`
			"
			:visible.sync="dialogFormVisible"
			:destroy-on-close="true"
			width="620px"
			class="rempadding"
			@close="clear"
			center
		>
			<el-divider></el-divider>
			<el-form
				ref="formSub"
				:model="dialogForm"
				label-width="auto"
				:rules="rules"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="dialogForm.merchantId"
						:placeholder="$t('common.components.select_merchant')"
						style="width: 330px"
						:disabled="title === $t('common.edit')"
					></merchant-select>
				</el-form-item>
				<!-- <el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantName"
					v-if="title === $t('common.edit')"
				>
					<span>
						{{ dialogForm.merchantName }}
					</span>
				</el-form-item> -->
				<el-form-item
					:label="`${$t('risk.windControl_type')}:`"
					prop="windControlType"
				>
					<el-select
						v-model="dialogForm.windControlType"
						size="medium"
						:placeholder="$t('common.all')"
						clearable
						:disabled="title === $t('common.edit')"
						@change="changeWindControlType()"
						@clear="clearDialogWindControlType()"
						style="width: 330px"
					>
						<el-option
							v-for="item in windLevelTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item
					:label="`${$t('risk.windControl_type')}:`"
					prop="windControlType"
					v-if="title === $t('common.edit')"
				>
					<span>
						{{ dialogForm.windControlTypeValue }}
					</span>
				</el-form-item> -->
				<el-form-item
					:label="`${$t('common.risk_control_level')}:`"
					prop="windControlLevelName"
				>
					<el-input
						v-model="dialogForm.windControlLevelName"
						type="text"
						style="width: 330px"
						:placeholder="$t('common.please_enter')"
						:maxlength="10"
						:disabled="selectWindControlStatus"
						v-input="{ name: 'symbols' }"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('risk.description')}:`"
					prop="description"
				>
					<el-input
						v-model="dialogForm.description"
						type="textarea"
						style="width: 330px"
						:maxlength="50"
						:disabled="selectWindControlStatus"
						v-input="{ name: 'noEmpty' }"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
// import { isHaveEmoji, notSpecial2 } from '@/utils/validate'
import MainContent from '@/components/MainContent/index.vue'

export default {
	name: routerNames.createRiskRank,
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		this.loadData = this.throttle(this.loadData, 1000)
		this.reset = this.throttle(this.reset, 1000)
		this._changeTableSort = this.throttle(this._changeTableSort, 1000)
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {
				windControlType: undefined,
				windControlLevelName: [],
				createdBy: undefined,
				updatedBy: undefined
			},
			tableData: [],
			windControlLevelNameArr: [],
			dialogFormVisible: false,
			dialogForm: {
				windControlLevelName: undefined,
				windControlType: undefined,
				merchantId: undefined,
				description: undefined
			},
			total: 0,
			title: '',
			selectWindContolType: true,
			selectWindControlStatus: true
		}
	},
	computed: {
		windLevelTypeArr() {
			return this.globalDics.windLevelType || []
		},
		rules() {
			return {
				windControlLevelName: [
					{
						required: true,
						message: this.$t(
							'member.please_fill_in_the_risk_control_level'
						),
						trigger: 'blur'
					}
				],
				windControlType: [
					{
						required: true,
						message: this.$t(
							'member.please_select__risk_control_type'
						),
						trigger: 'blur'
					}
				],
				merchantId: [
					{
						required: true,
						message: this.$t('member.please_select_a_merchant'),
						trigger: 'blur'
					}
				],
				description: [
					{
						required: true,
						message: this.$t(
							'risk.please_fill_in_the_risk_control_level_description'
						),
						trigger: 'blur'
					}
				]
			}
		},
		windControlLevelName() {
			return this.queryData.windControlLevelName
		}
	},
	watch: {
		windControlLevelName(newVal, oldVal) {
			const newIdx = newVal.indexOf('all')
			const oldIdx = oldVal.indexOf('all')
			if (newIdx !== -1 && oldIdx === -1 && newVal.length > 1) {
				this.queryData.windControlLevelName = ['all']
			} else if (newIdx !== -1 && oldIdx !== -1 && newVal.length > 1) {
				this.queryData.windControlLevelName.splice(
					newVal.indexOf('all'),
					1
				)
			}
		}
	},
	created() {
		// this.getMerchantDict('1')
		// this.queryData.windControlLevelName = ['all']
	},
	methods: {
		changeWindControlType() {
			if (this.dialogForm.windControlType !== undefined) {
				this.selectWindControlStatus = false
			} else {
				this.selectWindControlStatus = true
			}
		},
		// 弹框风控类型删除按钮事件
		clearDialogWindControlType() {
			this.selectWindControlStatus = true

		},
		// 搜索区风控类型删除按钮事件
		clearWindControlType() {
			this.selectWindContolType = true
		},
		loadData() {
			this.loading = true
			this.tableData = []
			let params = {
				...this.queryData
			}
			params = {
				...this.getParams(params)
			}
			// const idx = params.windControlLevelName.findIndex(
			// 	(item) => item === 'all'
			// )
			// params.windControlLevelName.splice(idx, 1)
			params.windControlLevelName =
				params.windControlLevelName &&
				params.windControlLevelName.length &&
				params.windControlLevelName[0] !== 'all'
					? params.windControlLevelName
					: undefined
			params.createdBy = params.createdBy ? params.createdBy : undefined
			params.updatedBy = params.updatedBy ? params.updatedBy : undefined
			this.$api
				.riskRankListAPI(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						const { record, totalRecord } = res.data || {}
						this.tableData = Array.isArray(record)
							? Object.freeze(record)
							: []
						this.total = totalRecord || 0
					} else {
						this.$message({
							message:
								res?.msg ||
								this.$t('agent.interface_exceptions'),
							type: 'error'
						})
					}
				})
				.catch(() => {
					this.loading = false
				})

			setTimeout(() => {
				this.loading = false
			}, 1000)
		},
		reset() {
			this.pageNum = 1
			this.$refs['form'].resetFields()
			this.windControlLevelNameArr = []
			this.queryData = {
				windControlType: undefined,
				windControlLevelName: [],
				createdBy: undefined,
				updatedBy: undefined
			}
			this.loadData()
			this.selectWindContolType = true
		},
		addLabel() {
			this.dialogFormVisible = true
			this.selectWindControlStatus = true
			this.$refs['form'].resetFields()
			this.title = this.$t('common.add')
			if (!this.$store.getters.isZk) {
				this.dialogForm.merchantId = this.$store.getters.merchantInfo.id
				this.dialogForm.windControlType = undefined
				this.dialogForm.windControlLevelName = undefined
				this.dialogForm.description = undefined
			} else {
				this.dialogForm = {
					windControlLevelName: undefined,
					windControlType: undefined,
					merchantId: undefined,
					description: undefined
				}
			}
		},
		edit(val) {
			this.title = this.$t('common.edit')
			val.windControlType = val.windControlType + ''
			this.dialogForm = { ...val }
			this.dialogFormVisible = true
			this.selectWindControlStatus = false
		},
		deleteLabel(val) {
			const { id } = val
			this.$confirm(
				`<strong>${this.$t(
					'risk.is_del_risk_level_tip'
				)}</strong><br/><strong style="color:#D9001B">${this.$t(
					'risk.del_risk_level_warning'
				)}</strong>`,
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning',
					customClass: 'positionIcon'
				}
			)
				.then(() => {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					this.$api
						.deleteRiskRankAPI({ id })
						.then((res) => {
							loading.close()
							if (res?.code === 200) {
								this.$message.success(
									this.$t('common.delete_success')
								)
								this.loadData()
							} else {
								this.$message({
									type: 'error',
									message: this.$t('common.delete_fail')
								})
							}
						})
						.catch(() => {
							loading.close()
						})
					setTimeout(() => {
						loading.close()
					}, 1000)
				})
				.catch(() => {})
		},
		subAddOrEdit() {
			const params = {
				...this.dialogForm
			}
			const handleClick =
				this.title !== this.$t('common.edit')
					? this.$api.createRiskRankAPI
					: this.$api.updateRiskRankAPI
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					handleClick(params).then((res) => {
						const { code, msg } = res
						if (code === 200) {
							this.$message({
								message: `${
									this.title !== this.$t('common.edit')
										? this.$t('common.add_success')
										: this.$t('common.edit_success')
								}`,
								type: 'success'
							})
							this.loadData()
						} else {
							this.$message({
								message: msg,
								type: 'error'
							})
						}
					})
					this.dialogFormVisible = false
				}
			})
		},
		clear() {
			this.dialogForm = {
				windControlLevelName: undefined,
				windControlType: undefined,
				merchantId: undefined,
				description: undefined
			}
		},
		// 获取风控层级
		getMerchantDict(val) {
			if (this.queryData.windControlType !== undefined) {
				this.selectWindContolType = false
			} else {
				this.selectWindContolType = true
			}
			this.queryData.windControlLevelName = []
			this.windControlLevelNameArr = []
			this.$api
				.getSelectWindControlLevel({
					merchantId: this.queryData.merchantId,
					windControlType: val * 1
				})
				.then((res) => {
					const { code, data, msg } = res || {}
					if (code === 200) {
						this.windControlLevelNameArr = data || []
					} else {
						this.$message({
							message: msg,
							type: 'error'
						})
					}
				})
		}
		// _getMerchantDict(val) {
		//     this.$api
		//         .getSelectWindControlLevel({
		//             windControlType: val * 1
		//         })
		//         .then((res) => {
		//             const { code, data, msg } = res || {}
		//             if (code === 200) {
		//                 this.vipDictOther = data || []
		//             } else {
		//                 this.$message({
		//                     message: msg,
		//                     type: 'error'
		//                 })
		//             }
		//         })
		// }
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .tagheight .el-tag {
	height: 24px;
	line-height: 24px;
	min-width: 60px;
}
::v-deep .rempadding .el-dialog__body {
	padding: 0;
	padding-bottom: 30px;

	.contentBox,
	form {
		padding: 0 20px;
	}
}
::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}
::v-deep .el-input-number--medium .el-input__inner {
	padding: 0 15px;
	text-align: left;
}
.decoration {
	text-decoration: underline;
	cursor: pointer;
}
.bodyBox {
	max-height: 400px;
	overflow: auto;
}
p {
	display: flex;
	height: 40px;
	line-height: 40px;
	border-bottom: 1px solid #e8e8e8;
	justify-content: space-around;
	span {
		display: inline-block;
		width: 50%;
		text-align: center;
	}
}
.headerBox {
	color: #000000d8;
	background: #fafafa;
	font-family: 'PingFang SC ', 'PingFang SC', sans-serif;
	font-weight: 650;
	border-top: 1px solid #e8e8e8;
	margin-top: 15px;
}
</style>
